﻿//
//Copyright (c) Seagull Consulting, Inc. All rights reserved. See License.txt in the project root for license information.
//
var MvcAjaxControls = function () { };
var baseUrl;
var baseFilterUrl;
var currentId;
var pageNbr = 1;
var pageSize = 0;
var filterProperty;
var filterPropertyValue;
var GridMode = { NORMAL: { value: 1 }, FILTER: { value: 2} };
var CurrentMode = GridMode.NORMAL;

MvcAjaxControls.prototype.alternatingRows = function () {
    $("#mainList tbody tr").removeClass("alt");
    $("#mainList tbody tr:odd").addClass("alt");
};

MvcAjaxControls.prototype.dropdownList = function (options) {
    //Get the data, then build the Dropdown list
    MvcAjaxControls.prototype.getLUTList({
        url: options.url,
        parent: options.parent,
        success: function (result) {
            MvcAjaxControls.prototype.buildDDL({ 
                result: result,
                ddl: options.ddl,
                parent: options.parent
                });
        }
    });
};

MvcAjaxControls.prototype.buildDDL = function (options) {
    //Empty the list
    $(options.ddl).empty();
    //Add each list item to the dropdown list
    $.each(options.result, function (key, val) {
        $(options.ddl).append(new Option(val.Name, val.Id));
        //$(options.ddl).append($('<option></option>').val(val.Id).html(val.Name));
    });

    //Following must be inside the Ajax success function, because call is Async
    //Don't forget to set the selected option based on the original value passed by the controller
    var originalValue = $(options.ddl).attr('originalValue');
    if (originalValue != null) {
        $(options.ddl).val($(options.ddl).attr('originalValue'));
    }
    else {
        $(options.ddl).removeAttr('selected').find('option:first').attr('selected', 'selected');;
        $(options.ddl).trigger('change');
    }
};

MvcAjaxControls.prototype.getLUTList = function (options) {
    //If parent, we need to subscribe to parents change event
    //and update the url to reflect dependency
    if (options.parent != null) {
        $(options.parent).change(function () {
            //Make the Ajax call
            ajaxGet({
                url: options.url + '/' + $(options.parent).val(),
                success: options.success
            });
        });
    }
    else {
        //Otherwise make the Ajax call
        ajaxGet({
            url: options.url,
            success: options.success
        });
    }
};

MvcAjaxControls.prototype.getLUTItemById = function (options) {
    //Make sure the calls aren't cached
    $.ajax({
        url: options.URL + options.Id,
        cache: false,
        type: 'GET',
        success: options.success,
        error: function (result) {
            displayError(result);
        }
    });
};

//show table
MvcAjaxControls.prototype.showMainList = function () {
    var id = checkForId();

    //Determine what mode we're running
    if (CurrentMode == GridMode.NORMAL) {
        //fix up the url if a id was passed in url
        if (id != null) {
            url = baseUrl + '/' + id + '?pageNbr=' + pageNbr + '&pageSize=' + pageSize;
        }
        else {
            url = baseUrl + '/?pageNbr=' + pageNbr + '&pageSize=' + pageSize;
        }
    }
    else {
        //fix up the url if a id was passed in url
        if (id != null) {
            url = baseFilterUrl + '/' + id + '?pageNbr=' + pageNbr + '&pageSize=' + pageSize + '&property=' + filterProperty + '&propertyValue=' + filterPropertyValue;
        }
        else {
            url = baseFilterUrl + '/?pageNbr=' + pageNbr + '&pageSize=' + pageSize + '&property=' + filterProperty + '&propertyValue=' + filterPropertyValue;
        }
    }
    ajaxGet({
        url: url,
        success: function (result) {
            $("#mainList tbody").empty();

            // Render the template with the Location data and insert
            // the rendered HTML under the "mainList" tbody element
            $("#mainList tbody").html(
                $("#listTemplate").render(result)
            );
            MvcAjaxControls.prototype.alternatingRows();
        }
    });
};

ajaxGet = function (options) {
    //Make the call un-cached
    $.ajax({
        url: options.url,
        cache: false,
        type: 'GET',
        success: options.success,
        error: function (result) {
            displayError(result);
        }
    });
};

//Set paging events
MvcAjaxControls.prototype.setPagingEvents = function (options) {
    baseUrl = options.url;
    pageNbr = options.pageNbr;
    pageSize = options.pageSize;

    $("#refresh").click(function () { refreshPage(); });
    $("#first").click(function () { firstPage(); });
    $("#prev").click(function () { previousPage(); });
    $("#next").click(function () { nextPage(); });
    $("#last").click(function () { lastPage(); });

    $("#pager").hover(function () {
        $(this).css('cursor', 'pointer');
    }, function () {
        $(this).css('cursor', 'auto');
    });
};

//Set filtering events
MvcAjaxControls.prototype.setFilterEvents = function (options) {
    baseFilterUrl = options.url;

    $("#filterButton").click(function () { processFilter(); });

    $("#filterButton").hover(function () {
        $(this).css('cursor', 'pointer');
    }, function () {
        $(this).css('cursor', 'auto');
    });
};

//move to first display page
processFilter = function () {
    //get all input elements and find the first one which isn't empty
    var inputElement;
    $('.filterInput').each(function (index) {
        if ($(this).val().length > 0) {
            inputElement = $(this);
            return false;
        }
    });
    //alert(inputElement.attr('id'));
    if (inputElement != null) {
        CurrentMode = GridMode.FILTER;
        pageNbr = 1;
        var property = inputElement.attr('id');
        filterProperty = property.substring(0, property.indexOf("_"));
        filterPropertyValue = inputElement.val();
        MvcAjaxControls.prototype.showMainList();
        showPageNbr();
    }
    else {
        CurrentMode = GridMode.NORMAL;
        pageNbr = 1;
        filterProperty = '';
        filterPropertyValue = '';
        MvcAjaxControls.prototype.showMainList();
        showPageNbr();
    }
};

//refresh display page
refreshPage = function () {
    MvcAjaxControls.prototype.showMainList();
    showPageNbr();
};

//move to first display page
firstPage = function () {
    pageNbr = 1;
    MvcAjaxControls.prototype.showMainList();
    showPageNbr();
};

//move to previous display page
previousPage = function () {
    if (pageNbr > 1) {
        pageNbr = pageNbr - 1;
        MvcAjaxControls.prototype.showMainList();
        showPageNbr();
    }
};

//move to next display page
nextPage = function () {
    var lastPage = 0;
    var countUrl;
    if (CurrentMode == GridMode.NORMAL) {
        countUrl = baseUrl + 'Count';
    }
    else {
        countUrl = baseFilterUrl + 'Count/?property=' + filterProperty + '&propertyValue=' + filterPropertyValue;
    }

    ajaxGet({
        url: countUrl,
        success: function (result) {
            var remainder = result % pageSize;
            if (remainder > 0)
            { lastPage = ((result - remainder) / pageSize) + 1; }
            else
            { lastPage = result / pageSize; }
            if (pageNbr < lastPage)
            { pageNbr = pageNbr + 1; }
            MvcAjaxControls.prototype.showMainList();
            showPageNbr();
        }
    });
};

//move to last display page
lastPage = function () {
    var countUrl;
    if (CurrentMode == GridMode.NORMAL) {
        countUrl = baseUrl + 'Count';
    }
    else {
        countUrl = baseFilterUrl + 'Count/?property=' + filterProperty + '&propertyValue=' + filterPropertyValue;
    }
    ajaxGet({
        url: countUrl,
        success: function (result) {
            var remainder = result % pageSize;
            if (remainder > 0)
            { pageNbr = ((result - remainder) / pageSize) + 1; }
            else
            { pageNbr = result / pageSize; }
            MvcAjaxControls.prototype.showMainList();
            showPageNbr();
        }
    });
};

//show page number
showPageNbr = function () {
    $("#pagenbr").text(pageNbr);
};

checkForId = function () {
    //If the uri has a filter id, return it
    var uri = document.location.href;
    var id = uri.substring(uri.lastIndexOf('/') + 1);
    if (IsNumeric(id)) {
        return id;
    }
    else {
        return null;
    }
};

IsNumeric = function (num) {
    return (num >= 0 || num < 0);
} 

displayError = function (result) {
    $('#errorDisplay').css('visibility', 'visible');
    $('#errorDisplay').show();
    $('#errorDisplay').html(result.responseText);
};